# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

import pymongo
from drug_data.items import ConedosItem,HealthyGuestItem,OnemedicineItem

class MongoPipeline:
    def open_spider(self,spider):
        self.client = pymongo.MongoClient(host='127.0.0.1',port=27017)  # 创建mongodb连接

    def process_item(self, item, spider):
        # 康爱多
        if isinstance(item, ConedosItem):
            # spider为指定数据库名.集合名.insert_one(插入一条数据)
            self.client.spider.conedos.insert_one(item)
        # 健客
        elif isinstance(item,HealthyGuestItem):
            self.client.spider.healthy.insert_one(item)
        # 一药网
        elif isinstance(item,OnemedicineItem):
            self.client.spider.oneyao.insert_one(item)

        return item

    def close_spider(self,spider):
        self.client.close()